package org.bt.common.validator.number.decimal;

import lombok.extern.slf4j.Slf4j;
import org.bt.common.validator.aspect.DecimalMin;

import javax.validation.ConstraintValidator;
import javax.validation.ConstraintValidatorContext;
import java.math.BigDecimal;

/**
 * Check that the number being validated is greater than or equal to the minimum
 * value specified.
 *
 * @author tongw
 */
@Slf4j
public abstract class AbstractDecimalMinValidator<T> implements ConstraintValidator<DecimalMin, T> {

    protected BigDecimal minValue;
    private boolean inclusive;

    @Override
    public void initialize(DecimalMin minValue) {
        try {
            this.minValue = new BigDecimal(minValue.value());
        } catch (NumberFormatException nfe) {
            log.error(minValue.value(), nfe);
        }
        this.inclusive = minValue.inclusive();
    }

    @Override
    public boolean isValid(T value, ConstraintValidatorContext constraintValidatorContext) {
        // null values are valid
        if (value == null) {
            return true;
        }

        int comparisonResult = compare(value);
        return inclusive ? comparisonResult >= 0 : comparisonResult > 0;
    }

    protected abstract int compare(T number);
}
